<template>
  <div>
    <!--工具栏-->
    <div class="crud-group">
      <!-- 搜索 -->
      <el-select
        v-model="clusterId"
        clearable
        size="small"
        placeholder="请选择集群"
        class="filter-item"
      >
        <el-option
          v-for="item in clusterLists"
          :key="item.key"
          :label="item.label"
          :value="item.value"
        />
      </el-select>
      <el-input
        v-model="mark"
        clearable
        size="small"
        placeholder="请输入名称"
        style="width:200px"
        class="filter-item"
      />
      <el-select
        v-model="databaseType"
        clearable
        size="small"
        placeholder="请选择数据库类型"
        class="filter-item"
      >
        <el-option
          v-for="item in databaseTypeLists"
          :key="item.key"
          :label="item.lable"
          :value="item.value"
        />
      </el-select>
      <div style="display: flex;">
        <el-button
          type="success"
          icon="el-icon-search"
          @click="search"
        >搜索</el-button>
        <el-button
          type="warning"
          icon="el-icon-refresh-left"
          @click="reset"
        >重置</el-button>
        <el-button
          type="primary"
          icon="el-icon-plus"
          @click="addClick"
        >新增</el-button>
      </div>
    </div>
    <!--表格渲染-->
    <el-table
      v-loading="loading"
      :data="clusterList"
      border
    >
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
      />
      <el-table-column
        prop="clusterName"
        label="集群名称"
        min-width="80px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="mark"
        label="名称"
        min-width="80px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="jdbcName"
        label="库名"
        min-width="80px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="databaseType"
        label="数据库类型"
        min-width="80px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="url"
        label="url"
        min-width="80px"
        show-overflow-tooltip
      />
      <el-table-column
        prop="username"
        label="jdbc用户名"
        min-width="80px"
        show-overflow-tooltip
      />
      <el-table-column
        label="是否禁用"
        align="center"
        prop="disabled"
      >
        <template slot-scope="scope">
          <el-switch
            v-model="scope.row.disabled"
            active-color="#ff4949"
            inactive-color="#dcdfe6"
            active-value="true"
            @change="changeEnabled(scope.row, scope.row.disabled)"
          />
        </template>
      </el-table-column>
      <el-table-column
        prop="comments"
        label="描述"
        min-width="80px"
        show-overflow-tooltip
      />
      <el-table-column
        width="100px"
        label="操作"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="editClick(scope.row)"
          >编辑</el-button>
          <el-button
            size="mini"
            type="text"
            @click="deleteClick(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination-container">
      <!--分页组件-->
      <el-pagination
        :current-page="current"
        :page-size="size"
        layout="prev, pager, next,sizes,total"
        :total="length"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 编辑表单 -->
    <el-dialog
      :close-on-click-modal="false"
      :before-close="closeEdit"
      :visible.sync="openEdit"
      :title="title"
      width="1000px"
    >
      <el-form
        ref="jqForm"
        :inline="true"
        label-width="180px"
        :rules="rules"
        :model="jqForm"
      >
        <el-form-item
          label="集群名称"
          prop="clusterId"
        >
          <el-select
            v-model="jqForm.clusterId"
            style="width: 210px"
            clearable
            size="small"
            placeholder="请选择集群"
            class="filter-item"
          >
            <el-option
              v-for="item in clusterLists"
              :key="item.key"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="名称"
          prop="mark"
        >
          <el-input
            v-model="jqForm.mark"
            style="width: 210px"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item
          label="库名"
          prop="jdbcName"
        >
          <el-tooltip
            content="若为初始化脚本配置发布数据库，请填写为【impala】"
            placement="top"
          >
            <el-input
              v-model="jqForm.jdbcName"
              style="width: 210px"
              placeholder="请输入"
            />
          </el-tooltip>
        </el-form-item>
        <el-form-item
          label="db-type"
          prop="dbType"
        >
          <el-input
            v-model="jqForm.dbType"
            :rows="2"
            type="textarea"
            disabled
            style="width: 210px"
            placeholder="请输入"
          />
        </el-form-item>
        <el-form-item
          label="数据库类型"
          prop="databaseType"
        >
          <el-autocomplete
            v-model="jqForm.databaseType"
            style="width: 210px;"
            class="inline-input"
            :popper-append-to-body="false"
            :fetch-suggestions="querydatabase"
            placeholder="请选择或输入数据库类型"
          />
        </el-form-item>
        <el-form-item
          label="数据库驱动"
          prop="driverclassname"
        >
          <el-autocomplete
            v-model="jqForm.driverclassname"
            class="inline-input"
            style="width: 210px;"
            :popper-append-to-body="false"
            :fetch-suggestions="querySearch"
            placeholder="请选择或输入数据库驱动"
            @select="handleSelect"
          />
        </el-form-item>
        <el-row>
          <el-col>
            <el-form-item
              label="url"
              prop="url"
            >
              <el-input
                v-model="jqForm.url"
                style="width: 610px"
                :rows="2"
                placeholder="请输入"
              />
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item
          label="jdbc用户名"
          prop="username"
        >
          <el-input
            v-model="jqForm.username"
            style="width: 210px"
            placeholder="请输入"
            type="text"
          />
        </el-form-item>
        <el-form-item
          label="jdbc密码"
          prop="password"
        >
          <el-input
            v-model="jqForm.password"
            placeholder="请输入"
            style="width: 210px"
            show-password
            autocomplete="new-password"
          />
        </el-form-item>
        <el-form-item
          label="描述"
          prop="comments"
        >
          <el-input
            v-model="jqForm.comments"
            :rows="5"
            type="textarea"
            style="width: 610px"
            placeholder="请输入"
          />
        </el-form-item>
      </el-form>
      <div style="margin-top: 30px;width:100%;text-align: center">
        <el-button
          type="primary"
          :loading="isTestingConnection"
          @click="connectTest"
        >测试连接</el-button>
        <el-button
          type="primary"
          plain
          @click="closeEdit"
        >取消</el-button>
        <el-button
          type="primary"
          @click="submit"
        >确认</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import jdbcConfigApi from '@/api/script/config/jdbcConfig'
import clusterSparingApi from '@/api/cluster/clusterSparing'

export default {
  name: 'DataDesensitizationRules',
  data() {
    return {
      loading: false,
      current: 1,
      size: 10,
      length: 0,
      clusterList: [],
      clusterLists: [],
      clusterName: '',
      isTestingConnection: false,
      driverclassnameList: [
        {'value': 'com.mysql.cj.jdbc.Driver'},
        {'value': 'oracle.jdbc.driver.OracleDriver'},
        {'value': 'org.apache.hive.jdbc.HiveDriver'},
        {'value': 'com.cloudera.impala.jdbc41.Driver'}],
      databaseTypes: [
        {'value': 'mysql'},
        {'value': 'oracle'},
        {'value': 'hive'},
        {'value': 'impala'}],
      databaseTypeLists: [],
      databaseType: '',
      mark: '',
      openEdit: false,
      clusterId: '',
      jqForm: {
        clusterId: '',
        mark: '',
        jdbcName: '',
        dbType: 'com.alibaba.druid.pool.DruidDataSource',
        driverclassname: '',
        url: '',
        username: '',
        password: '',
        disabled: '',
        comments: '',
        databaseType: ''
      },
      title: '',
      versionList: ['CDH 6.3.2 (Parcel)'],
      rules: {
        clusterId: [
          { required: true, message: '请选择集群名称', trigger: 'change' }
        ]
      }
    }
  },
  created() {
    this.initData()
  },
  methods: {
    changeType(e) {
    },
    initData(clusterId, mark, databaseType, resetPage) {
      this.clusterLists = []
      clusterSparingApi.findListByPage().then((res) => {
        const data = res.records
        data.forEach((array) => {
          this.clusterLists.push({ value: array.id, label: array.clusterName })
        })
      })
      this.databaseTypeLists = [{value: 'mysql', label: 'mysql'}, {value: 'impala', label: 'impala'}, {value: 'oracle', label: 'oracle'}, {value: 'hive', label: 'hive'}]

      if (resetPage) {
        this.current = 1
      }
      this.loading = true
      var data = {
        current: this.current,
        size: this.size,
        clusterId: clusterId,
        mark: mark,
        databaseType: databaseType
      }
      jdbcConfigApi.findListByPage(data)
        .then((data) => {
          console.log(data)
          this.length = data.totalElements
          if (data.content.length === 0) {
            this.jqForm = {}
          } else {
            this.jqForm = data.content[0]
          }
          this.clusterList = data.content
          this.loading = false
        })
        .catch(() => { })
    },
    search() {
      this.current = 1
      this.initData(this.clusterId, this.mark, this.databaseType)
    },
    reset() {
      this.current = 1
      this.clusterId = ''
      this.mark = ''
      this.databaseType = ''
      this.initData(this.clusterId, this.mark, this.databaseType)
    },
    // 分页
    handleSizeChange(val) {
      this.current = 1
      this.size = val
      this.initData()
    },
    // 分页
    handleCurrentChange(val) {
      this.current = val
      this.initData(null, null, null, false)
    },
    // 改变是否禁用状态
    changeEnabled(data, val) {
      this.$confirm('此操作将' + (val ? '禁用' : '取消禁用') + '此配置信息, 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        jdbcConfigApi.edit(data).then(res => {
          console.log(data)
        }).catch(() => {
          data.disabled = !data.disabled
        })
      }).catch(() => {
        data.disabled = !data.disabled
      })
    },
    // 数据库驱动输入建议方法
    querySearch(queryString, cb) {
      var restaurants = this.driverclassnameList
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    querydatabase(queryString, cb) {
      var restaurants = this.databaseTypes
      var results = queryString ? restaurants.filter(this.createFilter(queryString)) : restaurants
      // 调用 callback 返回建议列表的数据
      cb(results)
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) === 0)
      }
    },
    handleSelect(item) {
      console.log(item)
    },
    editClick(row) {
      this.title = '编辑'
      var temp = {
        mark: row.mark,
        jdbcName: row.jdbcName,
        dbType: row.dbType,
        driverclassname: row.driverclassname,
        databaseType: row.databaseType,
        url: row.url,
        username: row.username,
        password: row.password,
        clusterId: row.clusterId,
        id: row.id,
        comments: row.comments
      }
      this.jqForm = temp
      console.log(this.jqForm)
      this.openEdit = true
    },
    closeEdit() {
      this.openEdit = false
      this.$refs['jqForm'].resetFields()
      this.jqForm = {}
    },
    deleteClick(row) {
      const h = this.$createElement
      this.$msgbox(
        {
          title: '提示',
          message: h('p', null, [
            h('span', { style: 'color: red' }, '此条数据'),
            h('span', null, '为jdbc配置信息，是否删除？')
          ]),
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消'
        }
      ).then(() => {
        jdbcConfigApi.del(row.id).then((data) => {
          this.initData()
        })
      }).catch(() => {
        return
      })
    },
    submit() {
      this.$refs['jqForm'].validate((valid) => {
        if (valid) {
          if (this.title === '编辑') {
            jdbcConfigApi.edit(this.jqForm).then((data) => {
              this.initData()
              this.openEdit = false
            })
          } else {
            jdbcConfigApi.add(this.jqForm).then((data) => {
              this.initData()
              this.openEdit = false
              this.jqForm = {}
            })
          }
        } else {
          return false
        }
      })
    },
    connectTest() {
      this.$refs['jqForm'].validate((valid) => {
        if (valid) {
          this.isTestingConnection = true
          jdbcConfigApi.connectTest(this.jqForm).then((data) => {
            const mapInstance = new Map(Object.entries(data))
            if (data.hasOwnProperty('0')) {
              this.$message({
                message: mapInstance.get('0'),
                type: 'error'
              })
            } else {
              this.$message({
                message: mapInstance.get('1'),
                type: 'success'
              })
            }
          }).finally(() => {
            this.isTestingConnection = false
          })
        } else {
          return false
        }
      })
    },
    addClick() {
      this.jqForm = {dbType: 'com.alibaba.druid.pool.DruidDataSource'}
      this.title = '新增'
      this.openEdit = true
    }
  }
}
</script>
<style scoped>
.el-input{
  width: 200px;
}
 ::v-deep .el-autocomplete-suggestion{
  width: auto!important;
}
</style>
